﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OauthProvider;

namespace Chat_WebServer
{
    [Serializable]
    public class MiniRequestToken : TokenBase
    {
        public bool AccessDenied { get; set; }
        public bool UsedUp { get; set; }
        public MiniAccessToken AccessToken { get; set; }
        public string CallbackUrl { get; set; }
        public string Verifier { get; set; }

        public override string ToString()
        {
            string formattedToken = base.ToString();

            formattedToken += "&" + Parameters.OAuth_Callback_Confirmed + "=true";

            return formattedToken;
        }

        public override void SaveToken()
        {
            using (var db = new AccountEntities())
            {
                RequestToken tk = new RequestToken();
                tk.AccessDenied = AccessDenied.ToString();
                if (AccessToken != null)
                    tk.AccessToken = AccessToken.Token;
                tk.CallbackUrl = CallbackUrl;
                tk.ConsumerKey = ConsumerKey;
                tk.Realm = Realm;
                tk.TokenSecret = TokenSecret;
                tk.UsedUp = UsedUp.ToString();
                tk.Verifier = Verifier;
                tk.Token = Token;
                var requesttoken = db.RequestTokens.ToList().FirstOrDefault(r => r.Token == Token);
                if (requesttoken != null)
                {
                    requesttoken.AccessDenied = tk.AccessDenied;
                    requesttoken.AccessToken = tk.AccessToken;
                    requesttoken.CallbackUrl = tk.CallbackUrl;
                    requesttoken.ConsumerKey = tk.ConsumerKey;
                    requesttoken.Realm = tk.Realm;
                    requesttoken.Token = tk.Token;
                    requesttoken.TokenSecret = tk.TokenSecret;
                    requesttoken.UsedUp = tk.UsedUp;
                    requesttoken.Verifier = tk.Verifier;
                }
                else db.RequestTokens.AddObject(tk);
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new Exception("Can not save RequestToken because: " + ex.ToString());
                }
            }
        }
    }
}
